﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LanHomepage.ViewModels;
using System.Web.Security;
using BusinessLogic;
using System.IO;
using System.Drawing;

namespace LanHomepage.Controllers
{
    public class BaseController : Controller
    {
        private readonly IDatabaseHandler _databaseHandler;

        public BaseController(IDatabaseHandler databaseHandler) 
        {
            _databaseHandler = databaseHandler;
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Mainpage", "Main");
        }

        public ActionResult Login(BaseViewModel model)
        {
            if (_databaseHandler.ValidateUser(model.Username, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.Username, true);
            }

            return RedirectToAction("Mainpage", "Main");
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult FileUpload(HttpPostedFileBase file, string url)
        {
            if (file != null && file.ContentLength > 0)
            {
                if (Image.FromStream(file.InputStream, true, true).Width == 125)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Images/Sponsor"), fileName);
                    file.SaveAs(path);
                    _databaseHandler.SaveImage("/Images/Sponsor/" + fileName, url);
                }
            }
            return RedirectToAction("Mainpage", "Main");
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public bool DeleteSponsorLogo(string _id) 
        {
            return _databaseHandler.DeleteImage(_id);
        }

        /*
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var ctx = System.Web.HttpContext.Current;

            var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var actionName = filterContext.ActionDescriptor.ActionName;

            if(ctx.Session.IsNewSession && controllerName != "MainController" && actionName != "Login")
            {
                var sessionCookie = ctx.Request.Headers["Cookie"];
                if (sessionCookie != null && (sessionCookie.IndexOf("ASP.NET_SessionId", System.StringComparison.Ordinal) >= 0))
                {
                    FormsAuthentication.SignOut();
                    filterContext.Result = View("SessionExpired"); //session expired page perhaps
                }
            }

            base.OnActionExecuted(filterContext);
        }*/
    }
}
